// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import {
    Form,
    Row,
    Col,
    Input,
    Cascader,
    Tag,
    Icon,
    DatePicker,
    Select,
    Button,
    Upload,
    Modal,
    Divider,
    Tooltip,
    message,
    Radio, Checkbox
} from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
import {isEmpty, isArray, cloneDeep, chunk, set, get} from 'lodash'

// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
import { reg } from 'utils/util'
// 当前组件样式
import styles from './integralManagementDetailStyle.less'
import Uploader from "widget/Upload";
import classnames from 'classnames/bind'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import PopUpSelect from 'widget/PopUpSelectnoModal/PopUpSelect'
let cx = classnames.bind(styles);
const { Option } = Select;
const FormItem = Form.Item
const { TextArea } = Input
const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 16 },
}
const imageLayout = {
    labelCol: { span: 2 },
    wrapperCol: { span: 22 },
}

const routeView = function ({ dispatch, model, form }) {
    // 表单的子函数
    const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
    // 取出model对象，命名空间
    const { modelObj, namespace } = model
    let { merchandiseList, merchantList,pageType, isClone, formData,regionList,areaList,medias,selectAddressList} = modelObj
    // modelObj.xxx获取model中状态机的值

    // updateProduct createProduct
    function save() {
        let methodName={ edit: 'update', add: 'create', detail: '' }[pageType]
        if(isClone){//clone方式新建
            methodName='create'
        }
        validateFields((err) => {
            if (err) {
                return false
            } else {
                dispatch({
                    type: `${namespace}/${methodName}`,
                    payload: {resetFields}
                })
            }
        })
    }

    function updateImageModel(value) {
        medias.push(value);
        // 分发到model
        dispatch({
            type: `${namespace}/updateStore`,
            payload: { medias }
        })
    };

    function removeImgUrl(index) {
        medias.splice(index, 1)
        dispatch({
            type: `${namespace}/updateStore`,
            payload: { medias }
        })
    }

    function inputChange(value, type) {
        if(type == "regionId"){
            let data = regionList.filter(item=>{
                return item.regionId == value
            })
            formData.regionName = data[0].regionName;
        }
        if(type == "jfMerchantId"){
            let data = merchantList.filter(item=>{
                return item.value == value
            })
            formData.jfMerchantName = data[0].label;
        }
        if(type == "jfMerchandiseId"){
            let data = merchandiseList.filter(item=>{
                return item.value == value
            })
            formData.jfMerchandiseName = data[0].label;
        }
        formData[type] = value;
        form.resetFields();
        dispatch({
          type: `${namespace}/updateStore`,
          payload: { formData }
        })
    }

    function isUnionChange(value, type){
        if(value != '1'){
            formData.jfMerchantName = ''
            formData.jfMerchantId = ''
        }
        formData[type] = Number(value);
        form.resetFields();
        dispatch({
          type: `${namespace}/updateStore`,
          payload: { formData }
        })
    }

    /*
    ===================================兑换项目代码开始
    */
   const sellerTableColumn = [
        { title: '项目名称', width: 100, dataIndex: 'productName', key: 'productId',render:(e,item)=>{
            return item.productName ||item.name
        } },
        // { title: '所属城市',width:170, dataIndex: 'city', key: 'city' ,render:(a, item, index, d, e, f)=>{
        //     //console.log(item)
        //     let arr = ['北京市','重庆','上海','天津']
        //     if(arr.indexOf(item.provinceName)>-1){
        //         return `${item.cityName}`
        //     }else{
        //         return `${item.provinceName||''}${item.provinceName&&item.cityName&&' - '||''}${item.cityName||''}`
        //     }
        // }
        // },
        {
            title:'项目地址',width:200,dataIndex:'mapAddress',key:'mapAddress'
        }
    ];

    let sellerQueryList = [
        // {name: '区域公司', type: 'select', key: 'regionId',list:addressList,notNeedAll:true},
        { name: '省市', type: 'cascader', list: cloneDeep(areaList), key: ['province', 'city', 'county'], value: '' },
        { name: '项目名称', type: 'text', key: 'name', value: '' },
        { name: '', type: 'hidden', key: 'shelfStatus', value: '1' },
    ];

    const sellerSelectedColumn = [
        { title: '项目名称', width: 200, dataIndex: 'productName', key: 'productId' ,render:(e,item)=>{
            return  item.productName ||item.name
        }},
        // { title: '所属城市', dataIndex: 'cityName', key: 'cityName',render:(a, item, index, d, e, f)=>{
        //     //console.log(item)
        //     // console.log(item)
        //     let arr = ['北京','重庆','上海','天津']
        //     let provinceName=''
        //     let cityName=''
        //     // console.log(areaList.length)
        //     for(let i=1;i<areaList.length;i++){
        //         if(item.province==areaList[i].value){
        //             provinceName=areaList[i].label
        //             if(arr.indexOf(provinceName)>-1){
        //                 provinceName=''
        //             }
        //             for(let j=0;j<areaList[i].children.length;j++){
        //                 if(item.city==areaList[i].children[j].value){
        //                     cityName=areaList[i].children[j].label
        //                     // console.log(provinceName,cityName)
        //                     return <span>{`${provinceName}${provinceName && '-'}${cityName}`}</span>
        //                 }
        //             }
        //         }
        //     }
            
        // }},
        {
            title:'项目地址',width:280,dataIndex:'mapAddress',key:'mapAddress',render:(e,item)=>{
                return  item.mapAddress
            }
        }
        
    ];

    /*
    ============================兑换项目代码结束
    */

    return (
        <div className={cx('public_listMain')}>
            <div className="functionButton">
                {
                    pageType=='detail'?null:<Button type='primary' loading={modelObj.btnLoading} onClick={() => { save() }}>保存</Button>
                }
                
            </div>
            <CollapsiblePanels title="商品信息" hideUpDownBtn={true}>
                <div>
                    <Row className="col" >
                        <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label="选择区域">
                                {getFieldDecorator(`regionId`, {
                                    initialValue:  formData.regionId || '',
                                    rules: [
                                        { required: pageType!='detail', whitespace: true, message: '请选择区域' },
                                    ],
                                })((<Select
                                    disabled={pageType == 'detail'} 
                                  onChange={(e) => inputChange(e, 'regionId')}>
                                  {regionList.map((item,idx)=>{
                                      return <Select.Option key={item.key}  value={item.value}>{item.label}</Select.Option>
                                    })}
                                  
                                </Select>))}
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label="是否上架">
                                {getFieldDecorator(`issj`, {
                                    initialValue:  formData.issj || '',
                                    rules: [
                                        { required: pageType!='detail', whitespace: true, message: '请选择是否上架' },
                                    ],
                                })((<Select
                                    disabled={pageType == 'detail'} 
                                  onChange={(e) => inputChange(e, 'issj')}>
                                    <Select.Option value="Y">是</Select.Option>
                                    <Select.Option value="N">否</Select.Option>
                                </Select>))}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label='商品名称'>
                                {getFieldDecorator('giftName', {
                                    initialValue: formData.giftName,
                                    rules: [
                                        { required: pageType != 'detail',  message: '请输入商品名称'},
                                    ],
                                })(<Input
                                    disabled={pageType == 'detail'}
                                    placeholder={'请输入商品名称'}
                                    onChange={(e) => { inputChange(e.target.value, 'giftName') }}
                                />)}
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label="商品简介">
                                {getFieldDecorator(`giftJj`, {
                                    initialValue:  formData.giftJj || '',
                                    rules: [
                                        { required: false, whitespace: true, message: '请选择是否上架' },
                                    ],
                                })((<TextArea
                                    disabled={pageType == 'detail'} 
                                  onChange={(e) => inputChange(e.target.value, 'giftJj')}>
                                </TextArea>))}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label="商品类别">
                                {getFieldDecorator(`jfMerchandiseId`, {
                                    initialValue:  formData.jfMerchandiseId || '',
                                    rules: [
                                        { required: pageType!='detail', whitespace: true, message: '请选择商品类别' },
                                    ],
                                })((<Select
                                    disabled={pageType == 'detail'} 
                                  onChange={(e) => inputChange(e, 'jfMerchandiseId')}>
                                  {merchandiseList.map((item,idx)=>{
                                      return <Select.Option key={item.key}  value={item.value}>{item.label}</Select.Option>
                                    })}
                                  
                                </Select>))}
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label="是否支持邮寄">
                                {getFieldDecorator(`isPost`, {
                                    initialValue:  formData.isPost || '',
                                    rules: [
                                        { required: pageType!='detail', whitespace: true, message: '请选择是否上架' },
                                    ],
                                })((<Select
                                    disabled={pageType == 'detail'} 
                                  onChange={(e) => inputChange(e, 'isPost')}>
                                    <Select.Option value="Y">邮寄</Select.Option>
                                    <Select.Option value="N">自取</Select.Option>
                                </Select>))}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label='兑换积分'>
                                {getFieldDecorator('integral', {
                                    initialValue: formData.integral,
                                    rules: [
                                        { required: pageType != 'detail',  message: '请输入兑换积分'},
                                        { pattern: /^(0|[1-9][0-9]*)$/, message: '请输入整数' }
                                    ],
                                })(<Input
                                    disabled={pageType == 'detail'}
                                    placeholder={'请输入兑换积分'}
                                    onChange={(e) => { inputChange(e.target.value, 'integral') }}
                                />)}
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label='兑换数量限制'>
                                {getFieldDecorator('sumLimit', {
                                    initialValue: formData.sumLimit,
                                    rules: [
                                        { required: pageType != 'detail',  message: '请输入兑换数量限制'},
                                        { pattern: /^(0|[1-9][0-9]*)$/, message: '请输入整数' }
                                    ],
                                })(<Input
                                    disabled={pageType == 'detail'}
                                    placeholder={'请输入兑换数量限制'}
                                    onChange={(e) => { inputChange(e.target.value, 'sumLimit') }}
                                />)}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label="是否商家联盟">
                                {getFieldDecorator(`isUnion`, {
                                    initialValue:  formData.isUnion?formData.isUnion +'':'',
                                    rules: [
                                        { required: pageType!='detail', whitespace: true, message: '请选择是否商家联盟' },
                                    ],
                                })((<Select
                                    disabled={pageType == 'detail'} 
                                  onChange={(e) => isUnionChange(e, 'isUnion')}>
                                    <Select.Option value='1'>是</Select.Option>
                                    <Select.Option value='0'>否</Select.Option>
                                </Select>))}
                            </FormItem>
                        </Col>
                        <Col span={12} style={{display: formData.isUnion == 1?'block': 'none'}}>
                            <FormItem {...formItemLayout}
                                      label="商家名称">
                                {getFieldDecorator(`jfMerchantId`, {
                                    initialValue:  formData.jfMerchantId || '',
                                    rules: [
                                        { required: formData.isUnion == '1'&&pageType!='detail'? true: false, whitespace: true, message: '请选择商家名称' },
                                    ],
                                })((<Select
                                    disabled={pageType == 'detail'} 
                                  onChange={(e) => inputChange(e, 'jfMerchantId')}>
                                  {merchantList.map((item,idx)=>{
                                      return <Select.Option key={item.key}  value={item.value}>{item.label}</Select.Option>
                                    })}
                                  
                                </Select>))}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label='备注'>
                                {getFieldDecorator('remark', {
                                    initialValue: formData.remark,
                                    rules: [
                                        { required: false, whitespace: true,  message: '请输入备注'},
                                    ],
                                })(<Input
                                    disabled={pageType == 'detail'}
                                    placeholder={'备注'}
                                    onChange={(e) => { inputChange(e.target.value, 'remark') }}
                                />)}
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label='库存数量'>
                                {getFieldDecorator('stock', {
                                    initialValue: formData.stock,
                                    rules: [
                                        { required: false,  message: '请输入库存数量'},
                                        { pattern: /^(0|[1-9][0-9]*)$/, message: '请输入整数' }
                                    ],
                                })(<Input 
                                    disabled={pageType == 'detail'}
                                    placeholder={'请输入库存数量'}
                                    onChange={(e) => { inputChange(e.target.value, 'stock') }}
                                />)}
                            </FormItem>
                        </Col>
                    </Row>
                </div>
            </CollapsiblePanels>
            <CollapsiblePanels title="商品图" hideUpDownBtn={true}>
                <Row>
                    <FormItem {...imageLayout} label="商品图">
                        <Uploader uploadedUrls={medias}
                                  removeFileCbf={(index) => { removeImgUrl(index) }}
                                  uploadSuccessCbf={(imgUrl) => { updateImageModel(imgUrl) }}
                                  ossFolderName="admin/integral/pic"
                                  showType='6'
                                  fileType='image'
                                //   fileMaxSize='0.2'
                                  unsetWidth={true}
                                  minCropBoxWidth={399}
                                  minCropBoxHeight={232}
                                  maxFiles='3' />

                    </FormItem>

                    <Col span={12}>
            <span style={{ color: '#999', marginLeft: '4%' }}>
            图片分辨率需为399px*232px，支持jpg，png格式。
              </span>
                    </Col>
                </Row>
            </CollapsiblePanels>
            <CollapsiblePanels title="兑换项目地址" hideUpDownBtn={true}>
                <PopUpSelect
                    tableColumn={sellerTableColumn}
                    selectedColumn={sellerSelectedColumn}
                    selectedTableScroll={{ x: 320 }}
                    queryList={cloneDeep(sellerQueryList)}
                    isSave={true}
                    refreshByEnter={true}
                    requestUrl='admin/estate/adminList'
                    title='选择工程名称'
                    respListKey='rows'
                    idKey='productId'
                    onItem={selectAddressList}
                    onChange={(e) => {
                        // let productIds=[]
                        selectAddressList = [];
                        e.map((item)=>{
                            // productIds.push(item.productId);
                            // let p = {
                            //     projectAddr:item.mapAddress,
                            //     // province:item.province,
                            //     // provinceName:item.provinceName,
                            //     projectname:item.name && item.name!=""?item.name:item.productName,
                            //     // latitude:item.latitude,
                            //     // longitude:item.longitude,
                            //     // cityName:item.cityName,
                            //     // city:item.city,
                            //     projectid:item.productId,
                            //     // projectId:item.outerId||item.projectId,
                            //     // estatePhone:item.estatePhone
                            // };

                            let p = {
                                mapAddress:item.mapAddress,
                                productName:item.name && item.name!=""?item.name:item.productName,
                                productId:item.productId,
                            };
                            selectAddressList.push(p);
                        })
                        dispatch({
                            type: `${namespace}/updateStore`,
                            payload: {selectAddressList}
                        })
                    }}
                ></PopUpSelect>
            </CollapsiblePanels>
        </div>
    )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))